package com.yicong.ants.manager.http;

import com.cchao.simplelib.LibCore;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import okhttp3.OkHttpClient;

/**
 * 网络管理类
 */
public class HttpManager {
    /**
     * get请求
     *
     * @param url
     * @param params
     * @param callback
     */
    public static void getHttp(String url, Map<String, String> params, Callback callback) {
        OkHttpUtils
            .initClient(INSTANCE.okHttpClient)
            .get()
            .url(url)
            .params(params)
            .build()
            .execute(callback);
    }

    /**
     * post请求
     *
     * @param url
     * @param params
     * @param callback
     */
    public static void postHttp(String url, Map<String, String> params, Callback callback) {
        OkHttpUtils
            .initClient(INSTANCE.okHttpClient)
            .post()
            .url(url)
            .params(params)
            .build()
            .execute(callback);
    }

    /**
     * 上传文件
     *
     * @param url
     * @param params
     * @param file
     * @param fileName
     * @param callback
     */
    public static void postFile(String url, Map<String, String> params, File file, String fileName, Callback callback) {
        Map<String, String> header = new HashMap<>(1);
        header.put("enctype", "multipart/form-data");
        OkHttpUtils
            .initClient(INSTANCE.okHttpClient)
            .post()
            .addFile("file", fileName, file)
            .url(url)
            .params(params)
            .headers(header)
            .build()
            .connTimeOut(10000)
            .readTimeOut(10000)
            .writeTimeOut(10000)
            .execute(callback);
    }

    private static class INSTANCE {
        static OkHttpClient okHttpClient = LibCore.getInfo().getOkHttpClient();
    }
}
